package com.guangzhoujiayou.jwt;

import com.guangzhoujiayou.utils.DateUtil;
import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * jtw工具类
 */
public class JWTHelper {

    private static RsaKeyHelper rsaKeyHelper = new RsaKeyHelper();
    /**
     * 密钥加密token
     *
     * @param map
     * @param priKeyStr
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(String subject,Map<String,Object> map, String priKeyStr, int expire) throws Exception {
        return generateToken(subject, map, RsaKeyHelper.toBytes(priKeyStr), expire);
    }

    /**
     * 密钥加密token
     *
     * @param subject
     * @param priKey
     * @param expire
     * @return
     * @throws Exception
     */
    public static String generateToken(String subject,Map<String,Object> map, byte priKey[], int expire) throws Exception {
        JwtBuilder builder = Jwts.builder();
        if (!StringUtils.isEmpty(subject)){
            builder.setSubject(subject);
        }
        if (null != map && !map.isEmpty()) {
            builder.addClaims(map);
        }
        return  builder //设置过期时间（单位秒）plusSeconds 加上秒数
                .setExpiration(DateUtil.toDate(LocalDateTime.now().plusSeconds(expire)))
                //加密
                .signWith(SignatureAlgorithm.RS256, rsaKeyHelper.getPrivateKey(priKey))
                //组成
                .compact();
    }

    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, String pubKeyStr) throws Exception {
        return parserToken(token, RsaKeyHelper.toBytes(pubKeyStr));
    }
    /**
     * 公钥解析token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(rsaKeyHelper.getPublicKey(pubKey)).parseClaimsJws(token);
        return claimsJws;
    }
    /**
     * 获取token中的用户信息
     *
     * @param token
     * @param pubKeyStr
     * @return
     * @throws Exception
     */
    public static Claims getInfoFromToken(String token, String pubKeyStr) throws Exception {
        return getInfoFromToken(token, RsaKeyHelper.toBytes(pubKeyStr));
    }
    /**
     * 获取token中的用户信息
     *
     * @param token
     * @param pubKey
     * @return
     * @throws Exception
     */
    public static Claims getInfoFromToken(String token, byte[] pubKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, pubKey);
        return claimsJws.getBody();
    }
}
